package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyQuery;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StatsResult;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 主页控制
 */
@Controller
@RequestMapping("/strategy")
public class StrategyController {
    @Reference
    private IRegionService regionService;
    @Reference
    private IStrategyCatalogService strategyCatalogService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IStrategyContentService strategyContentService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyTagService strategyTagService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;
    @Reference
    private IStrategyCommendService strategyCommendService;
    @Reference
    private IStrategySearchService strategySearchService;

    @RequestMapping("")
    //访问主页,跳转
    public String index(Model model) {
        //commends  推荐攻略 5篇
        List<StrategyCommend> list = strategyCommendService.listTop5();
        model.addAttribute("commends", list);
<<<<<<< HEAD


=======
>>>>>>> origin/zhiwei
        //upCds 飙升排行榜   阅读+评论的降序
        //查询redis中存储的zset数据,key为strategy_stats_up_sort,name为攻略的key,score为阅读和评论的和
        List<StrategyStats> upCds = strategyStatsCacheService.listRankTOP10(RedisKey.STRATEGY_STATS_UP_SORT);
        model.addAttribute("upCds", upCds);
<<<<<<< HEAD

        //hotCds 热门排行榜  点赞+收藏的降序
        List<StrategyStats> hotCds = strategyStatsCacheService.listRankTOP10(RedisKey.STRATEGY_STATS_HOT_SORT);
        model.addAttribute("hotCds", hotCds);

=======
        //hotCds 热门排行榜  点赞+收藏的降序
        List<StrategyStats> hotCds = strategyStatsCacheService.listRankTOP10(RedisKey.STRATEGY_STATS_HOT_SORT);
        model.addAttribute("hotCds", hotCds);
>>>>>>> origin/zhiwei
        //ThemeCds  主题推荐
        List<Map<String, Object>> themeCds = strategySearchService.themeCommends();
        model.addAttribute("themeCds", themeCds);
        //unabroads 国内
        List<StatsResult> unabroads = strategySearchService.listConditions(SearchQueryObject.CONDITION_UNABROAD);
        model.addAttribute("unabroads", unabroads);
        //abroads  国外
        List<StatsResult> abroads = strategySearchService.listConditions(SearchQueryObject.CONDITION_ABROAD);
        model.addAttribute("abroads", abroads);
        //themes  主题
        List<StatsResult> themes = strategySearchService.listConditions(SearchQueryObject.CONDITION_THEME);
        model.addAttribute("themes", themes);
        return "/strategy/index";
    }

    @RequestMapping("/list")
    public String index(@ModelAttribute("qo") StrategyQuery qo, Model model) {
        //吐司
        List<Destination> toasts = destinationService.toastsList(qo.getDestId());
        model.addAttribute("toasts", toasts);
        //目的地
        Destination destination = toasts.remove(toasts.size() - 1);
        model.addAttribute("dest", destination);
        //标签列表
        List<StrategyTag> tags = strategyTagService.selectByDestId(qo.getDestId());
        model.addAttribute("tags", tags);
        //分页
        PageInfo pageInfo = strategyDetailService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "/strategy/list";
    }


    @RequestMapping("/detail")
    public String detail(Long id, @LoginUser UserInfo userInfo, Model model) {
        StrategyDetail detail = strategyDetailService.get(id);
        StrategyContent content = strategyContentService.get(id);
        detail.setStrategyContent(content);
        model.addAttribute("detail", detail);


        //阅读攻略的逻辑,阅读数加1
        strategyStatsCacheService.incr(id, 1, IStrategyStatsCacheService.VIEWNUM_TYPE);
        //更新排行榜
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, 1, id);
        //共享vo对象
        StrategyStats stats = strategyStatsCacheService.get(id);
        model.addAttribute("vo", stats);
        //回显收藏效果
        boolean isFavor = userInfo != null && strategyStatsCacheService.isFavor(id, userInfo.getId());
        model.addAttribute("isFavor", isFavor);

        return "/strategy/detail";
    }

    @RequiredLogin
    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentAdd(StrategyComment entity, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        //填充信息
        try {
            entity.setUserId(userInfo.getId());
            entity.setUsername(userInfo.getNickname());
            entity.setHeadUrl(userInfo.getHeadImgUrl());
            entity.setLevel(userInfo.getLevel());
            //调用方法保存信息
            strategyCommentService.save(entity);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        //评论攻略的逻辑,;评论数加1
        strategyStatsCacheService.incr(entity.getDetailId(), 1, IStrategyStatsCacheService.REPLYNUM_TYPE);
        //更新飙升榜
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, 1, entity.getDetailId());
        //获取评论数
        StrategyStats stats = strategyStatsCacheService.get(entity.getDetailId());
        Integer replynum = stats.getReplynum();
        return result.addData(replynum);
    }

    @RequestMapping("/comment")
    public String comment(StrategyCommentQuery qo, Model model) {
        Page page = strategyCommentService.findByDetailId(qo);
        model.addAttribute("page", page);
        return "/strategy/commentTpl";
    }

    @RequiredLogin
    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(Long fromId, String toId) {
        strategyCommentService.commentThumbUp(fromId, toId);
        return new AjaxResult();
    }

    @RequiredLogin
    @RequestMapping("/favor")
    @ResponseBody
    //收藏操作
    public Object favor(Long strategyId, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        //查询当前攻略的收藏数
        StrategyStats stats = null;
        try {
            //调用收藏服务,返回标记,区分收藏和取消收藏
            boolean success = strategyStatsCacheService.favor(strategyId, userInfo.getId());
            //设置进result,共享给页面
            result.setSuccess(success);
            //更新热门榜
            if (success) {
                //收藏数加1
                strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, 1, strategyId);
            } else {
                //收藏数减1
                strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, -1, strategyId);
                //删除用户收藏关系
                strategyDetailService.deleteCollection(strategyId);
            }
            stats = strategyStatsCacheService.get(strategyId);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(102);
        }
        return result.addData(stats.getFavornum());
    }


    //点赞
    @RequiredLogin
    @RequestMapping("/strategyThumbup")
    @ResponseBody
    //点赞操作
    public Object strategyThumbup(Long strategyId, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        try {
            //调用服务,返回结果
            boolean success = strategyStatsCacheService.strategyThumbup(strategyId, userInfo.getId());
            //设置进result,共享给页面
            result.setSuccess(success);
            //点赞成功
            if (success) {
                //点赞数加1
                strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, 1, strategyId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(102);
        }
        //查询当前攻略的统计结果
        StrategyStats stats = strategyStatsCacheService.get(strategyId);
        return result.addData(stats.getThumbsupnum());
    }

    @RequestMapping("/searchPage")
    public String searchPage(SearchQueryObject qo, Model model) {
        Page<StrategyTemplate> page = strategySearchService.query(qo);
        model.addAttribute("page", page);
        return "/strategy/searchPageTpl";
    }

    //统计分享数
    @RequestMapping("/strategyShare")
    @ResponseBody
    public Object strategyShare(Long strategyId, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        //分享数+1
        strategyStatsCacheService.incr(strategyId, 1, IStrategyStatsCacheService.SHARENUM_TYPE);

        StrategyStats stats = strategyStatsCacheService.get(strategyId);

        result.addData(stats.getSharenum());
        return result;
    }

}
